//
//  EScrollerView.m
//  icoiniPad
//
//  Created by Ethan on 12-11-24.
//
//

#import "EScrollerView.h"
#import "HomeAdvertEntity.h"
//#import "UIImageView+WebCache.h"
#import "UIImageView+LK.h"
#import "UIButton+WebCache.h"
#import "TopBannerEntity.h"

@implementation EScrollerView
@synthesize delegate;

-(id)initWithFrameRect:(CGRect)rect ImageArray:(NSArray *)imgArr TitleArray:(NSArray *)titArr
{
	if ((self=[super initWithFrame:rect])) {
        
        self.userInteractionEnabled=YES;
        titleArray = titArr;
        NSMutableArray *tempArray=[NSMutableArray arrayWithArray:imgArr];
        if (imgArr != nil && imgArr.count > 0) {
            [tempArray insertObject:[imgArr objectAtIndex:([imgArr count]-1)] atIndex:0];
            [tempArray addObject:[imgArr objectAtIndex:0]];
        }
        
		imageArray=[NSArray arrayWithArray:tempArray];
		viewSize = rect;
        NSUInteger pageCount = [imageArray count];
        scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, rect.size.width, rect.size.height)];
        scrollView.pagingEnabled = YES;
        scrollView.contentSize = CGSizeMake(rect.size.width * pageCount, rect.size.height);
        scrollView.showsHorizontalScrollIndicator = NO;
        scrollView.showsVerticalScrollIndicator = NO;
        scrollView.scrollsToTop = NO;
        scrollView.delegate = self;
        scrollView.bounces=NO;
        for (int i = 0; i < pageCount; i++) {
//            UIImageView *imgView=[[UIImageView alloc] init];
            UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(viewSize.size.width*i, 0,viewSize.size.width, viewSize.size.height)];
            btn.adjustsImageWhenHighlighted = NO;
            HomeAdvertEntity *ad = [imageArray objectAtIndex:i];
            if ([ad.album hasPrefix:@"http://"]) {
                //网络图片 请使用ego异步图片库
//                imgView.imageURL = [NSURL URLWithString:ad.album];
                [btn sd_setImageWithURL:[NSURL URLWithString:ad.album] forState:UIControlStateNormal];
                
//                [imgView setImageWithURL:[NSURL URLWithString:ad.album]
//                        placeholderImage:[UIImage imageNamed:@"banner_02.png"]
//                                 options:SDWebImageCacheMemoryOnly];
            } else {
                UIImage *img=[UIImage imageNamed:ad.album];
                [btn setBackgroundImage:img forState:UIControlStateNormal];
            }
            if (i ==0) {
                btn.tag = pageCount -2;
            }else if (i == pageCount-1) {
                btn.tag = 0;
            }else {
                btn.tag = i -1;
            }
            
            [btn addTarget:self action:@selector(imagePressed:) forControlEvents:UIControlEventTouchUpInside];
            [scrollView addSubview:btn];
        }
        
        [scrollView setContentOffset:CGPointMake(viewSize.size.width, 0)];
        [self addSubview:scrollView];
        
        //说明文字层
        UIView *noteView=[[UIView alloc] initWithFrame:CGRectMake(0, self.bounds.size.height-33,self.bounds.size.width,33)];
//        [noteView setBackgroundColor:[UIColor colorWithRed:0.8 green:0.8 blue:0.8 alpha:0.5]];
        [noteView setBackgroundColor:[UIColor clearColor]];
        float pageControlWidth = (pageCount -2)*10.0f+40.f;
        float pagecontrolHeight = 20.0f;
        pageControl = [[DWPageControl alloc]initWithFrame:CGRectMake((self.frame.size.width/2-pageControlWidth/2),9, pageControlWidth, pagecontrolHeight)];
        pageControl.currentPage = 0;
        pageControl.numberOfPages = pageCount -2;
        [noteView addSubview:pageControl];
        
        noteTitle=[[UILabel alloc] initWithFrame:CGRectMake(5, 6, self.frame.size.width-pageControlWidth-15, 20)];
        //[noteTitle setText:[titleArray objectAtIndex:0]];
        [noteTitle setBackgroundColor:[UIColor clearColor]];
        [noteTitle setFont:[UIFont systemFontOfSize:13]];
        [noteView addSubview:noteTitle];
        noteView.userInteractionEnabled = NO;
        [self addSubview:noteView];
        
//        [NSTimer scheduledTimerWithTimeInterval:1 target: self selector: @selector(handleTimer:)  userInfo:nil  repeats: YES];
        [self addTimer];
	}
	return self;
}

/**
 *  从本地获取图片的加载方法
 */
- (id)initWithFrameRect1:(CGRect)rect topBannerEntityArr:(NSArray *)entityArr
{
    if ((self=[super initWithFrame:rect])) {
        
        self.userInteractionEnabled = YES;
        NSMutableArray *tempArray=[NSMutableArray arrayWithArray:entityArr];
        if (entityArr != nil && entityArr.count > 0) {
            
            [tempArray insertObject:[entityArr objectAtIndex:([entityArr count]-1)] atIndex:0];
            [tempArray addObject:[entityArr objectAtIndex:0]];
        }
        imageArray = [NSArray arrayWithArray:tempArray];
        viewSize = rect;
        NSUInteger pageCount = [imageArray count];
        scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, rect.size.width, rect.size.height)];
        scrollView.pagingEnabled = YES;
        scrollView.contentSize = CGSizeMake(rect.size.width * pageCount, rect.size.height);
        scrollView.showsHorizontalScrollIndicator = NO;
        scrollView.showsVerticalScrollIndicator = NO;
        scrollView.scrollsToTop = NO;
        scrollView.delegate = self;
        scrollView.bounces=NO;
        for (int i = 0; i < pageCount; i++) {
            //            UIImageView *imgView=[[UIImageView alloc] init];
            UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(viewSize.size.width*i, 0,viewSize.size.width, viewSize.size.height)];
            btn.adjustsImageWhenHighlighted = NO;
            TopBannerEntity *ad = [imageArray objectAtIndex:i];
            NSString *path = [NSString stringWithFormat:@"%@/Library/Caches/lyss/park_%@/%@",NSHomeDirectory(),ad.parkId,ad.album];
            UIImage *image = [UIImage imageWithContentsOfFile:path];
            [btn setBackgroundImage:image forState:UIControlStateNormal];
            if (i ==0) {
                btn.tag = pageCount -2;
            }else if (i == pageCount-1) {
                btn.tag = 0;
            }else {
                btn.tag = i -1;
            }
//            btn.enabled = NO;
//            [btn addTarget:self action:@selector(imagePressed:) forControlEvents:UIControlEventTouchUpInside];
            [scrollView addSubview:btn];
        }
        
        [scrollView setContentOffset:CGPointMake(viewSize.size.width, 0)];
        [self addSubview:scrollView];
        
        //说明文字层
        UIView *noteView=[[UIView alloc] initWithFrame:CGRectMake(0, self.bounds.size.height-33,self.bounds.size.width,33)];
        //        [noteView setBackgroundColor:[UIColor colorWithRed:0.8 green:0.8 blue:0.8 alpha:0.5]];
        [noteView setBackgroundColor:[UIColor clearColor]];
        float pageControlWidth = (pageCount -2)*10.0f+40.f;
        float pagecontrolHeight = 20.0f;
        pageControl = [[DWPageControl alloc]initWithFrame:CGRectMake((self.frame.size.width/2-pageControlWidth/2),9, pageControlWidth, pagecontrolHeight)];
        pageControl.currentPage = 0;
        pageControl.numberOfPages = pageCount -2;
        [noteView addSubview:pageControl];
        
        noteTitle=[[UILabel alloc] initWithFrame:CGRectMake(5, 6, self.frame.size.width-pageControlWidth-15, 20)];
        //[noteTitle setText:[titleArray objectAtIndex:0]];
        [noteTitle setBackgroundColor:[UIColor clearColor]];
        [noteTitle setFont:[UIFont systemFontOfSize:13]];
        [noteView addSubview:noteTitle];
        noteView.userInteractionEnabled = NO;
        [self addSubview:noteView];
        
        //        [NSTimer scheduledTimerWithTimeInterval:1 target: self selector: @selector(handleTimer:)  userInfo:nil  repeats: YES];
        [self addTimer];
    }
    return self;
}


-(id)initWithFrameRect2:(CGRect)rect ImageArray:(NSArray *)imgArr TitleArray:(NSArray *)titArr
{
    if ((self=[super initWithFrame:rect])) {
        
        self.userInteractionEnabled=YES;
        titleArray = titArr;
        NSMutableArray *tempArray=[NSMutableArray arrayWithArray:imgArr];
        [tempArray insertObject:[imgArr objectAtIndex:([imgArr count]-1)] atIndex:0];
        [tempArray addObject:[imgArr objectAtIndex:0]];
        imageArray=[NSArray arrayWithArray:tempArray];
        viewSize = rect;
        NSUInteger pageCount = [imageArray count];
        scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, viewSize.size.width, viewSize.size.height)];
        scrollView.pagingEnabled = YES;
        scrollView.contentSize = CGSizeMake(viewSize.size.width * pageCount, viewSize.size.height);
        scrollView.showsHorizontalScrollIndicator = NO;
        scrollView.showsVerticalScrollIndicator = NO;
        scrollView.scrollsToTop = NO;
        scrollView.delegate = self;
        
        for (int i = 0; i < pageCount; i++) {
            //            UIImageView *imgView=[[UIImageView alloc] init];
            UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(viewSize.size.width*i, 0,viewSize.size.width, viewSize.size.height)];
            btn.adjustsImageWhenHighlighted = NO;
            HomeAdvertEntity *ad = [imageArray objectAtIndex:i];
            if ([ad.album hasPrefix:@"http://"]) {
                //网络图片 请使用ego异步图片库
                //                imgView.imageURL = [NSURL URLWithString:ad.album];
                [btn sd_setImageWithURL:[NSURL URLWithString:ad.album] forState:UIControlStateNormal];
                
                //                [imgView setImageWithURL:[NSURL URLWithString:ad.album]
                //                        placeholderImage:[UIImage imageNamed:@"banner_02.png"]
                //                                 options:SDWebImageCacheMemoryOnly];
            } else {
                UIImage *img=[UIImage imageNamed:ad.album];
                [btn setBackgroundImage:img forState:UIControlStateNormal];
            }
            if (i ==0) {
                btn.tag = pageCount -2;
            }else if (i == pageCount-1) {
                btn.tag = 0;
            }else {
                btn.tag = i -1;
            }
            [btn addTarget:self action:@selector(imagePressed2:) forControlEvents:UIControlEventTouchUpInside];
            [scrollView addSubview:btn];
        }
        
        [scrollView setContentOffset:CGPointMake(viewSize.size.width, 0)];
        [self addSubview:scrollView];
        
        //说明文字层
        UIView *noteView=[[UIView alloc] initWithFrame:CGRectMake(0, self.bounds.size.height-23,self.bounds.size.width,10)];
        //        [noteView setBackgroundColor:[UIColor colorWithRed:0.8 green:0.8 blue:0.8 alpha:0.5]];
        [noteView setBackgroundColor:[UIColor clearColor]];
        float pageControlWidth = (pageCount)*10.0f+40.f;
        float pagecontrolHeight = 10.0f;
        pageControl = [[DWPageControl alloc]initWithFrame:CGRectMake((self.frame.size.width/2-pageControlWidth/2),9, pageControlWidth, pagecontrolHeight)];
        pageControl.currentPage = 0 ;
        pageControl.numberOfPages = pageCount -2;
        [noteView addSubview:pageControl];
        
        noteTitle=[[UILabel alloc] initWithFrame:CGRectMake(5, 6, self.frame.size.width-pageControlWidth-15, 10)];
        //[noteTitle setText:[titleArray objectAtIndex:0]];
        [noteTitle setBackgroundColor:[UIColor clearColor]];
        [noteTitle setFont:[UIFont systemFontOfSize:13]];
        noteView.userInteractionEnabled = NO;
        [noteView addSubview:noteTitle];
        [self addSubview:noteView];
        
        //        [NSTimer scheduledTimerWithTimeInterval:1 target: self selector: @selector(handleTimer:)  userInfo:nil  repeats: YES];
        [self addTimer];
    }
    return self;
}


-(id)initWithFrameRect:(CGRect)rect ImageStringArray:(NSArray *)imgArr TitleStringArray:(NSArray *)titArr
{
    if ((self=[super initWithFrame:rect])) {
        
        self.userInteractionEnabled=YES;
        titleArray = titArr;
        NSMutableArray *tempArray=[NSMutableArray arrayWithArray:imgArr];
        [tempArray insertObject:[imgArr objectAtIndex:([imgArr count]-1)] atIndex:0];
        [tempArray addObject:[imgArr objectAtIndex:0]];
        imageArray=[NSArray arrayWithArray:tempArray];
        viewSize = rect;
        NSUInteger pageCount = [imageArray count];
        scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, rect.size.width, rect.size.height)];
        scrollView.pagingEnabled = YES;
        scrollView.contentSize = CGSizeMake(rect.size.width * pageCount, rect.size.height);
        scrollView.showsHorizontalScrollIndicator = NO;
        scrollView.showsVerticalScrollIndicator = NO;
        scrollView.scrollsToTop = NO;
        scrollView.delegate = self;
        
        for (int i = 0; i < pageCount; i++) {
            //            UIImageView *imgView=[[UIImageView alloc] init];
            UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(viewSize.size.width*i, 0,viewSize.size.width, viewSize.size.height)];
            btn.adjustsImageWhenHighlighted = NO;
            NSString *ad = [imageArray objectAtIndex:i];
            if ([ad hasPrefix:@"http://"]) {
                //网络图片 请使用ego异步图片库
                //                imgView.imageURL = [NSURL URLWithString:ad.album];
                [btn sd_setImageWithURL:[NSURL URLWithString:ad] forState:UIControlStateNormal];
                
                //                [imgView setImageWithURL:[NSURL URLWithString:ad.album]
                //                        placeholderImage:[UIImage imageNamed:@"banner_02.png"]
                //                                 options:SDWebImageCacheMemoryOnly];
            } else {
                UIImage *img=[UIImage imageNamed:ad];
                [btn setBackgroundImage:img forState:UIControlStateNormal];
            }
            if (i ==0) {
                btn.tag = pageCount -1;
            }else if (i == pageCount) {
                btn.tag = 0;
            }else {
                btn.tag = i -1;
            }
            
            [btn addTarget:self action:@selector(imagePressed:) forControlEvents:UIControlEventTouchUpInside];
            [scrollView addSubview:btn];
        }
        
        [scrollView setContentOffset:CGPointMake(viewSize.size.width, 0)];
        [self addSubview:scrollView];
        
        //说明文字层
        UIView *noteView=[[UIView alloc] initWithFrame:CGRectMake(0, self.bounds.size.height-33,self.bounds.size.width,33)];
        //        [noteView setBackgroundColor:[UIColor colorWithRed:0.8 green:0.8 blue:0.8 alpha:0.5]];
        [noteView setBackgroundColor:[UIColor clearColor]];
        float pageControlWidth = (pageCount -2)*10.0f+40.f;
        float pagecontrolHeight = 20.0f;
        pageControl = [[DWPageControl alloc]initWithFrame:CGRectMake((self.frame.size.width/2-pageControlWidth/2),9, pageControlWidth, pagecontrolHeight)];
        pageControl.currentPage = 0;
        pageControl.numberOfPages = pageCount -2;
        [noteView addSubview:pageControl];
        
        noteTitle=[[UILabel alloc] initWithFrame:CGRectMake(5, 6, self.frame.size.width-pageControlWidth-15, 20)];
        //[noteTitle setText:[titleArray objectAtIndex:0]];
        [noteTitle setBackgroundColor:[UIColor clearColor]];
        [noteTitle setFont:[UIFont systemFontOfSize:13]];
        [noteView addSubview:noteTitle];
        noteView.userInteractionEnabled = NO;
        [self addSubview:noteView];
        
        //        [NSTimer scheduledTimerWithTimeInterval:1 target: self selector: @selector(handleTimer:)  userInfo:nil  repeats: YES];
        [self addTimer];
    }
    return self;
}


- (void)scrollViewDidScroll:(UIScrollView *)sender
{
    
    CGFloat pageWidth = scrollView.frame.size.width;
    int page = floor((scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
    currentPageIndex=page;
    pageControl.currentPage=(page-1);

    if ([titleArray count]> 0) {
        int titleIndex=page-1;
        if (titleIndex==[titleArray count]) {
            titleIndex=0;
        }
        if (titleIndex<0) {
            titleIndex=[titleArray count]-1;
        }
        [noteTitle setText:[titleArray objectAtIndex:titleIndex]];
    }


}
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self removeTimer];
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)_scrollView
{
    if (currentPageIndex==0) {
        [_scrollView setContentOffset:CGPointMake(([imageArray count]-2)*viewSize.size.width, 0)];
    }
    if (currentPageIndex==([imageArray count]-1)) {
        [_scrollView setContentOffset:CGPointMake(viewSize.size.width, 0)];
    }
    [self addTimer];
}
- (void)imagePressed:(id)sender
{
    UIButton *btn = (UIButton *)sender;
    if ([delegate respondsToSelector:@selector(EScrollerViewDidClicked:)]) {
        [delegate EScrollerViewDidClicked:btn.tag];
        
        DebugLog(@"11111111111111111111");
    }
}
- (void)imagePressed2:(id)sender
{
    UIButton *btn = (UIButton *)sender;
    if ([delegate respondsToSelector:@selector(EScrollerViewDidClicked2:)]) {
        [delegate EScrollerViewDidClicked2:btn.tag];
        
        DebugLog(@"222222222222222222222");
    }
}

#pragma mark - 5秒换图片
- (void) handleTimer: (NSTimer *) timer
{
//    if (TimeNum % 5 == 0 ) {
        if (!Tend) {
            pageControl.currentPage++;
            if (pageControl.currentPage==pageControl.numberOfPages-1) {
                Tend=YES;
            }
        }else{
            pageControl.currentPage--;
            if (pageControl.currentPage==0) {
                Tend=NO;
            }
        }
        
        [UIView animateWithDuration:0.5 //速度0.7秒
                         animations:^{//修改坐标
                             scrollView.contentOffset = CGPointMake((pageControl.currentPage+1)*SCREEN_WIDTH,0);
                         }];
//    }
    
//    TimeNum ++;
}
- (void)addTimer
{
    [self removeTimer];
    
    self.timer = [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(handleTimer:) userInfo:nil repeats:YES];
}

- (void)removeTimer
{
    [self.timer invalidate];
    self.timer = nil;
}
@end
